package com.feihao.zhou.demo01;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectAndConstructor {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        /*//获取Class对象：
        Class<?> clazz = Class.forName("com.feihao.zhou.demo01.Student");

        //获取空参构造对象：
        Constructor<?> constructor = clazz.getConstructor();
        Student student = (Student) constructor.newInstance();
        System.out.println("空参构造创建的对象：" + student);

        //获取带参构造：
        Constructor<?> constructor1 = clazz.getConstructor(String.class, int.class);
//        Student student2 = (Student) constructor1.newInstance();
        Student student1 = (Student) constructor1.newInstance("张三", 18);
        System.out.println("带参的构造创建的对象：" + student1);

        //获取私有的构造：
        Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(int.class);
        //暴力解除private限制，取消访问检查
        declaredConstructor.setAccessible(true);
        Student student2 = (Student) declaredConstructor.newInstance(18);
        System.out.println("私有的构造创建的对象" + student2);*/

        //1.获取Class对象：
        Class<?> clazz = Class.forName("com.feihao.zhou.demo01.Student");
        //2.获取空参构造：
        Constructor<?> constructor = clazz.getConstructor();

        //3.使用空参构造对象创建Student对象
        Student student = (Student) constructor.newInstance();
        System.out.println(student);

        //获取带参构造：
        Constructor<?> constructor1 = clazz.getConstructor(String.class, int.class);
        Student student1 = (Student) constructor1.newInstance("小三",18);//带参构造，创建对象需赋值
        System.out.println(student1);

        //获取所有的构造方法：
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }

        //获取私有构造，并创建对象：
        Constructor<?> privateConstructor = clazz.getDeclaredConstructor(int.class);
        privateConstructor.setAccessible(true);//设置访问安全检查为true
        Object o = privateConstructor.newInstance(18);
        Student student2 = (Student)o;
        System.out.println(student2);


    }
}
